package com.clementheliou.cheliou.web.controller.gallery.technicaldatasheet.comment.model;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.clementheliou.cheliou.business.dataaccess.comment.CommentDataAccessService;
import com.clementheliou.cheliou.dal.model.comment.Comment;

/**
 * <i>Primefaces</i> {@link LazyDataModel} dedicated to the comment's data grid.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link Comment};
 * @see {@link Component};
 * @see {@link LazyDataModel};
 * @see {@link Scope}.
 * @since 1.0
 */
@Component
@Scope("session")
public class CommentLazyDataModel extends LazyDataModel<Comment> {

	/**
	 * Logger for this class.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link Logger};
	 * @see {@link LoggerFactory}.
	 * @since 1.0
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(CommentLazyDataModel.class);

	/**
	 * UID for serialization.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	private static final long serialVersionUID = -2522000822271242699L;

	/**
	 * Service about the comments.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link Autowired}.
	 * @since 1.0
	 */
	@Autowired
	private transient CommentDataAccessService commentService;

	/**
	 * The identifier of the photo the comments are related to.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	private Integer photoId;

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public List<Comment> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
		LOGGER.debug("Lazy loading for the photo {} with first {} and page size of {}.", new Object[] { photoId, first, pageSize });
		Assert.notNull(photoId, "A photo identifier must be provided at this time.");

		setRowCount(commentService.countCommentsOfPhoto(photoId));
		return commentService.getCommentsOfPhoto(photoId, first, pageSize);
	}

	/*
	 * Getters & setters.
	 */

	public void setPhotoId(Integer photoId) {
		this.photoId = photoId;
	}

}
